<template>
  <div class="cart-page">
    <van-sticky :container="container">
      <div class="cart-header">
        <div class="cart-top clearfix">
          <h3 class="fl">购物车</h3>
          <span class="fr">管理</span>
        </div>
        <p class="cart-info">共 {{totalNum}} 件宝贝 <span>收货地址：云南省昆明市官渡区撒法发是否</span></p>
      </div>
    </van-sticky>
    <!-- <van-empty description="暂无数据" /> -->
    <div class="cart-goods">
      <div class="shop-item"
           v-for="(shop,shopIdx) in state.cartList">
        <h4 class="shop-name">
          <van-icon name="shop-o"
                    class="m-primary" /> {{shop.unit_name}}
          <van-icon name="arrow to-right"
                    class="m-info" />
        </h4>
        <van-swipe-cell v-for="(good,goodIdx) in shop.goodsArr">
          <van-row>
            <van-col span="3"
                     class="checkbox-wrapper">
              <van-checkbox v-model="good.isChecked"
                            @change="handleCheckedGoods(good,good.isChecked)"
                            checked-color="#d41e32" />
            </van-col>
            <van-col span="21">
              <van-card class="goods-card"
                        :num="good.number"
                        :price="good.money"
                        :desc="'型号： '+ good.model_name"
                        :title="good.goods_name"
                        :thumb="state.ossUrl + good.img">
                <!-- <template #tags>
                  <div class="tag-wrapper">
                    <van-tag
                      plain
                      color="#d41e32"
                    >三年质保</van-tag>
                    <van-tag
                      plain
                      color="#d41e32"
                    >消费者权益保障</van-tag>
                    <van-tag
                      plain
                      color="#d41e32"
                    >72消失内发货</van-tag>
                    <van-tag
                      plain
                      color="#d41e32"
                    >品牌认证商家</van-tag>
                    <van-tag
                      plain
                      color="#d41e32"
                    >退货无忧</van-tag>
                  </div>
                </template> -->
                <template #num>
                  <van-stepper v-model="good.number"
                               theme="round"
                               integer
                               input-width="20px"
                               button-size="20px"
                               @change="handleEditGoodsNum(good)" />
                </template>
              </van-card>
            </van-col>
          </van-row>
          <template #right>
            <van-button square
                        text="删除"
                        type="danger"
                        class="delete-button"
                        @click="handleRemoveGoods(good.id,state)" />
          </template>
        </van-swipe-cell>
      </div>
    </div>
    <van-submit-bar :price="totalPrice"
                    button-text="提交订单"
                    @submit="onSubmit">
      <van-checkbox v-model="state.checkedAll"
                    checked-color="#d41e32"
                    @change="checkedAllGoods">全选</van-checkbox>
      <template #tip>
        你的收货地址不支持同城送, <span @click="onClickEditAddress">修改地址</span>
      </template>
    </van-submit-bar>
  </div>
</template>

<script>
import {
  reactive,
  onMounted,
  computed,
  watch,
  watchEffect,
  getCurrentInstance,
} from "vue";

import {
  getCartData,
  deleteModelFromCart,
  editModelFromCart,
} from "/@api/index";
import { useRouter } from "vue-router";
export default {
  name: "Cart",
  data () {
    return {
      container: null,
    };
  },
  mounted () {
    this.container = this.$refs.container;
  },
  setup () {
    const { ctx } = getCurrentInstance();
    const { push } = useRouter();
    const state = reactive({
      checkedList: [],
      checkedAll: false,
      cartList: [],
      ossUrl: "https://pms-uploads1.oss-cn-chengdu.aliyuncs.com",
    });
    onMounted(async () => {
      await initCartListData(state);
    });
    // 将所有选择框存入一个数组
    let checkedAllArr = computed(() => {
      let arr = [];
      for (let i = 0; i < state.cartList.length; i++) {
        const element = state.cartList[i];
        for (let j = 0; j < element.goodsArr.length; j++) {
          const item = element.goodsArr[j];
          arr.push(item.isChecked);
        }
      }
      return arr;
    });
    // 商品总数
    let totalNum = computed(() => {
      let num = 0;
      for (let i = 0; i < state.cartList.length; i++) {
        const element = state.cartList[i];
        for (let j = 0; j < element.goodsArr.length; j++) {
          const item = element.goodsArr[j];
          num += item.number;
        }
      }
      return num;
    });
    // 根据所有商品选择状态决定全选的状态
    watch(checkedAllArr, (val) => {
      const isTrue = val.every((val) => {
        return val;
      });
      if (isTrue) {
        state.checkedAll = true;
      }
      const isFalse = val.every((val) => {
        return !val;
      });
      if (isFalse) {
        state.checkedAll = false;
      }
    });
    // 是否选中所有商品
    const checkedAllGoods = (val) => {
      if (val) {
        for (let i = 0; i < state.cartList.length; i++) {
          const element = state.cartList[i];
          for (let j = 0; j < element.goodsArr.length; j++) {
            const item = element.goodsArr[j];
            item.isChecked = true;
          }
        }
      } else {
        for (let i = 0; i < state.cartList.length; i++) {
          const element = state.cartList[i];
          for (let j = 0; j < element.goodsArr.length; j++) {
            const item = element.goodsArr[j];
            item.isChecked = false;
          }
        }
      }
    };
    // 选中商品
    const handleCheckedGoods = (val, isAdd) => {
      if (isAdd) state.checkedList.push(val);
      if (!isAdd) {
        state.checkedList = state.checkedList.filter((item) => {
          return item.goods_id != val.goods_id;
        });
      }
      console.log(val);
      console.log(state.checkedList);
    };
    // 选中商品总价
    const totalPrice = computed(() => {
      let price = 0;
      state.checkedList.map((item) => {
        price += item.number * item.money;
      });
      return price * 100;
    });
    // 删除商品型号
    const handleRemoveGoods = async (id, state) => {
      console.log(id);
      await deleteModelFromCart({ id: id });
      await initCartListData(state);
    };
    // 编辑商品数量
    const handleEditGoodsNum = async (goods) => {
      await editModelFromCart({ id: goods.id, number: goods.number });
    };

    // 提交选中商品
    const onSubmit = () => {
      console.log(state.checkedList);
    };
    return {
      state,
      push,
      totalNum,
      totalPrice,
      handleCheckedGoods,
      checkedAllGoods,
      handleRemoveGoods,
      handleEditGoodsNum,
      onSubmit,
    };
  },
};
const initCartListData = async (state) => {
  const { data } = await getCartData();
  // state.cartList = data.data.row;
  let goodsArr = [];
  for (let i = 0; i < data.data.row.length; i++) {
    let shop = data.data.row[i];
    let shopItem = {
      unit_id: shop.goods_unit_id,
      brand_name: shop.brand_name,
      unit_name: shop.unit_name,
      total_money: shop.total_money,
      goodsArr: [],
    };
    for (let j = 0; j < shop.goodsArr.length; j++) {
      let good = shop.goodsArr[j];
      for (let k = 0; k < good.modelArr.length; k++) {
        let model = good.modelArr[k];
        const goodItem = {
          id: model.id,
          unit_id: shopItem.unit_id,
          goods_name: good.goods_name,
          pms_code: good.pms_code,
          goods_id: good.goods_id,
          img: good.img,
          img_z_logo2: good.img_z_logo2,
          model_name: model.model,
          model_id: model.model_id,
          money: model.money,
          number: model.number,
          size: model.size,
          stock: model.stock,
        };
        if (goodItem.unit_id == shopItem.unit_id)
          shopItem.goodsArr.push(goodItem);
      }
    }
    goodsArr.push(shopItem);
  }
  console.log(goodsArr);
  state.cartList = goodsArr;
};
</script>

<style scoped lang="less">
.cart-page {
  .cart-header {
    padding-bottom: 5px;
    border-radius: 5px;
    background-color: rgb(238, 238, 238);
    .cart-top {
      padding: 0 10px;
      color: #fff;
      line-height: 54px;
      background-color: #d41e32;
      h3 {
        float: left;
        font-size: 1.8rem;
      }
    }
    .cart-info {
      padding: 0 10px;
      color: #999;
      font-size: 0.5rem;
      margin-top: 8px;
    }
  }
  .cart-goods {
    padding: 0 10px;
    padding-bottom: 84px;
    .shop-item {
      padding: 8px 0;
      margin: 10px 0;
      border-radius: 10px;
      background-color: rgb(250, 250, 250);
      .shop-name {
        text-align: left;
        padding: 0 20px;
        margin-bottom: 15px;
        .van-icon {
          position: relative;
          top: 2px;
          &:last-child {
            right: -15px;
            top: 0px;
            font-size: 0.5rem;
          }
        }
      }
      .checkbox-wrapper {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .van-swipe-cell {
      border-radius: 5px;
      .goods-card {
        padding-left: 0;
        .tag-wrapper {
          transform: scale(0.9);
          transform-origin: 0 0;

          ::v-deep(.van-tag) {
            @tag-font-size: 8px;
            margin: 0 3px 3px 0;
          }
        }
      }

      .delete-button {
        height: 100%;
      }
    }
  }
  .van-submit-bar {
    bottom: 49px;
  }
}
</style>
